import { BasePromiseResultType } from '#/request'
import { RequestStatus } from '@/enums/request'
import useToastMsg from '@/hooks/sysMsg'
import useUserInfoStore from '@/store/userInfo'
import { getPlatformInfo } from '@/utils/platform'

const userInfoStore = useUserInfoStore()
const toastMsg = useToastMsg()

// 存储请求记录：key为请求唯一标识，value为最后一次请求时间戳
const requestRecord = new Map<string, number>()
// 防抖时间间隔（毫秒）
const DEBOUNCE_INTERVAL = 1000

const useResponseInterceptor = {
  successHooks: (res: any): Promise<any> => {
    if (res.data.code === RequestStatus.SUCCESS) {
      return Promise.resolve(res)
    }
    return Promise.resolve(false)
  },
  errorHooks: (res: any): Promise<any> => Promise.reject(false),
}

// 生成请求唯一标识（基于method、url和参数）
const getRequestKey = (method: string, url: string, params: any, data: any) => {
  // 合并参数并转换为字符串作为标识一部分
  const paramsStr = JSON.stringify(params || {})
  const dataStr = JSON.stringify(data || {})
  return `${method}-${url}-${paramsStr}-${dataStr}`
}

const useRequestInterceptor = (method: string, url: string, params: any, data: any, header?: any, responesData?: any): any => {
  let token = ''
  console.log('userInfoStore.getPlatformType', userInfoStore.getPlatformType)
  if (userInfoStore.getPlatformType == 'khd') {
    token = uni.getStorageSync('token')
  } else if (userInfoStore.getPlatformType == 'tzr') {
    token = uni.getStorageSync('shtzrToken')
  } else if (userInfoStore.getPlatformType == 'gld') {
    token = uni.getStorageSync('shToken')
  }
  const requestData: any = {
    url: getPlatformInfo().baseUrl + url,
    method,
    data: params || data,
    timeout: 6000,
    header: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json',
      'content-encoding': 'gzip',
      'token': token,
      ...header,
    },
  }

  if (responesData) {
    Object.keys(responesData).forEach((item) => (requestData[item] = responesData[item]))
  }

  return requestData
}

export const getRequest = <T>(method: string, url: string, params: any, data: any, header?: any, responesData?: any): Promise<BasePromiseResultType<T>> => {
  // 生成当前请求的唯一标识
  const requestKey = getRequestKey(method, url, params, data)
  const now = Date.now()
  const lastRequestTime = requestRecord.get(requestKey) || 0

  // 检查是否在防抖时间内
  if (now - lastRequestTime < DEBOUNCE_INTERVAL) {
    return Promise.resolve([null, '操作过于频繁，请稍后再试'])
    // return Promise.reject(new Error('操作过于频繁，请稍后再试'))
  }
  // 更新请求记录时间戳
  requestRecord.set(requestKey, now)

  return new Promise((resolve) => {
    uni.request({
      ...useRequestInterceptor(method, url, params, data, header, responesData),
      success: async (res: any) => {
        const result = await useResponseInterceptor.successHooks(res)
        if (result) {
          resolve([result.data, null])
        } else {
          resolve([null, res.msg || res.data.msg])
        }
      },
      fail: async (err: any) => {
        const result = useResponseInterceptor.errorHooks(err)
        resolve([null, err.message])
      },
    })
  })
}
